package com.yunpeng.aidevice.biz.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.yunpeng.aidevice.biz.service.IUserBizService;
import com.yunpeng.aidevice.common.constant.QueryConstants;
import com.yunpeng.aidevice.common.dto.query.UserQueryDTO;
import com.yunpeng.aidevice.common.dto.save.UserSaveDTO;
import com.yunpeng.aidevice.common.enums.ResultCodeEnum;
import com.yunpeng.aidevice.common.enums.UserStateEnum;
import com.yunpeng.aidevice.common.vo.SimpleEntityVO;
import com.yunpeng.aidevice.common.vo.user.MerchantLoginUserVO;
import com.yunpeng.aidevice.common.vo.user.UserBasicInfoVO;
import com.yunpeng.aidevice.dao.constant.DictionariesConstant;
import com.yunpeng.aidevice.dao.model.entity.OrganizationDO;
import com.yunpeng.aidevice.dao.model.entity.UserDO;
import com.yunpeng.aidevice.dao.service.IListQueryService;
import com.yunpeng.aidevice.dao.service.IOrganizationService;
import com.yunpeng.aidevice.dao.service.IUserService;
import com.yunpeng.common.dto.Result;
import com.yunpeng.common.enums.QueryOperatorEnum;
import com.yunpeng.common.paging.PagingQueryDTO;
import com.yunpeng.common.paging.query.QueryParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * UserBizServiceImpl 用户业务服务
 *
 * @author : Moore(hemw)
 * @date : 2020-04-13
 */
@Service
public class UserBizServiceImpl implements IUserBizService {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(UserBizServiceImpl.class);

    @Resource
    private IUserService userService;

    @Resource
    private IOrganizationService organizationService;

    @Resource
    private IListQueryService listQueryService;


    @Override
    /**
     * 新增用户
     *
     * @param userSaveDTO  用户信息
     * @param operatorCode 操作人代码
     * @return
     */
    public Result<Void> addNewUser(UserSaveDTO userSaveDTO, String operatorCode) {
        if (userService.addNewUser(userSaveDTO, operatorCode)) {
            return Result.success();
        }
        LOGGER.error("could not save new user info ,user {}", userSaveDTO);
        return Result.fail(ResultCodeEnum.SAVE_DATA_FAILED);
    }


    @Override
    /**
     * 更新用户基础信息
     *
     * @param userSaveDTO 更新信息
     * @param operator    操作人
     * @return
     */
    public Result<Void> updateUserBasicInfo(UserSaveDTO userSaveDTO, String operator) {
        if (userService.updateBasicInfo(userSaveDTO, operator)) {
            return Result.success();
        }
        return Result.fail(ResultCodeEnum.SAVE_DATA_FAILED);
    }

    @Override
    /**
     * 获取用户基本信息
     *
     * @param userCode     用户代码
     * @param merchantCode 商户代码
     * @return
     */
    public Result<UserBasicInfoVO> getUserBasicInfo(String userCode, String merchantCode) {
        UserDO userDO = userService.getByCode(userCode, merchantCode, DictionariesConstant.INSTANCE.getDefaultTenantCode());
        if (userDO == null || userDO.getId() == null) {
            LOGGER.error("could not get user info ,user code {}", userCode);
            return Result.fail(ResultCodeEnum.DATA_ACCESS_FAIL);
        }
        UserBasicInfoVO userBasicInfoVO = new UserBasicInfoVO();
        userBasicInfoVO.setUserCode(userDO.getCode());
        userBasicInfoVO.setOrgCode(userDO.getOrganizationCode());
        userBasicInfoVO.setOrgName(userDO.getOrganizationName());
        userBasicInfoVO.setUserNumber(userDO.getNumber());
        userBasicInfoVO.setUserName(userDO.getName());
        userBasicInfoVO.setSex(userDO.getSex());
        userBasicInfoVO.setPhone(userDO.getPhone());
        userBasicInfoVO.setEmail(userDO.getEmail());
        if (StringUtils.isNotBlank(userDO.getFaceImgUrl())) {
            try {
                JSONArray faceImgArray = JSONArray.parseArray(userDO.getFaceImgUrl());
                userBasicInfoVO.setFaceImgUrl(faceImgArray.toJavaList(String.class));
            } catch (Exception ex) {
                LOGGER.error("translate face img url str to list array.", ex);
            }
        }
        userBasicInfoVO.setInvalidDate(userDO.getInvalidDate());
        userBasicInfoVO.setState(userDO.getState());
        userBasicInfoVO.setStateDesc(UserStateEnum.getEnumLabelByValue(userDO.getState()));
        return Result.success(userBasicInfoVO);
    }

    @Override
    /**
     * 更新用户绑定组织信息
     *
     * @param userCodes        用户代码集合
     * @param organizationCode 组织机构代码
     * @param operatorUser     操作人代码
     * @param merchantCode     商户代码
     * @return
     */
    public Result<Void> usersBindOrganization(List<String> userCodes, String organizationCode, String operatorUser, String merchantCode) {
        OrganizationDO organizationDO = organizationService.getByCode(organizationCode, merchantCode, DictionariesConstant.INSTANCE.getDefaultTenantCode());
        if (organizationDO == null || organizationDO.getId() == null) {
            LOGGER.error("could not get organization info ,organization code {}", organizationCode);
            return Result.build(ResultCodeEnum.NOT_EXISTS_DATA_FAILED.getValue(), "无此组织");
        }
        if (userService.userBindToOrganization(userCodes, organizationDO, operatorUser)) {
            return Result.success();
        }
        LOGGER.error("update organization info error,organization code {},users {}", organizationCode, userCodes);
        return Result.fail(ResultCodeEnum.SAVE_DATA_FAILED);
    }

    @Override
    /**
     * 商户端用户列表
     *
     * @param userQueryDTO 用户查询对象
     * @return
     */
    public Result<PagingQueryDTO> queryUserList(UserQueryDTO userQueryDTO) {
        PagingQueryDTO pagingQueryDTO = new PagingQueryDTO();
        List<QueryParam> queryParams = new ArrayList<>();
        LinkedHashMap<String, String> orderByMap = new LinkedHashMap<>(16);
        //组织机构代码
        if (StringUtils.isNotBlank(userQueryDTO.getOrgCode())) {
            queryParams.add(QueryParam.quickSetQueryParam("organization_code",
                    userQueryDTO.getOrgCode(), QueryOperatorEnum.EQUALS));
        }
        //用户编号
        if (StringUtils.isNotBlank(userQueryDTO.getUserNumber())) {
            queryParams.add(QueryParam.quickSetQueryParam("number",
                    userQueryDTO.getUserNumber(), QueryOperatorEnum.EQUALS));
        }
        //用户名
        if (StringUtils.isNotBlank(userQueryDTO.getUserName())) {
            queryParams.add(QueryParam.quickSetQueryParam("name",
                    userQueryDTO.getUserName(), QueryOperatorEnum.LEFT_LIKE));
        }
        //用户电话
        if (StringUtils.isNotBlank(userQueryDTO.getPhone())) {
            queryParams.add(QueryParam.quickSetQueryParam("phone",
                    userQueryDTO.getPhone(), QueryOperatorEnum.EQUALS));
        }
        //用户邮箱
        if (StringUtils.isNotBlank(userQueryDTO.getEmail())) {
            queryParams.add(QueryParam.quickSetQueryParam("email",
                    userQueryDTO.getEmail(), QueryOperatorEnum.EQUALS));
        }
        //用户性别
        if (userQueryDTO.getSex() != null) {
            queryParams.add(QueryParam.quickSetQueryParam("sex",
                    userQueryDTO.getSex(), QueryOperatorEnum.EQUALS));
        }
        //用户生效时间起始
        if (userQueryDTO.getInvalidDateStart() != null) {
            queryParams.add(QueryParam.quickSetQueryParam("invalid_date",
                    userQueryDTO.getInvalidDateStart(), QueryOperatorEnum.GREATER_THAN));
        }
        //用户生效时间截止
        if (userQueryDTO.getInvalidDateEnd() != null) {
            queryParams.add(QueryParam.quickSetQueryParam("invalid_date",
                    userQueryDTO.getInvalidDateEnd(), QueryOperatorEnum.LESS_THAT_AND_EQUALS));
        }
        //用户状态
        if (StringUtils.isNotBlank(userQueryDTO.getState())) {
            queryParams.add(QueryParam.quickSetQueryParam("state",
                    userQueryDTO.getState(), QueryOperatorEnum.EQUALS));
        }
        //商户
        queryParams.add(QueryParam.quickSetQueryParam("merchant_code",
                userQueryDTO.getMerchantCode(), QueryOperatorEnum.EQUALS));
        //租户
        queryParams.add(QueryParam.quickSetQueryParam("tenant_code",
                userQueryDTO.getTenantCode(), QueryOperatorEnum.EQUALS));
        queryParams.add(QueryParam.quickSetQueryParam("flag", 1, QueryOperatorEnum.EQUALS));
        orderByMap.put("t.update_time", "t.desc");
        orderByMap.put("t.id", "desc");
        pagingQueryDTO.setCurrentPage(userQueryDTO.getCurrentPage());
        pagingQueryDTO.setPageSize(userQueryDTO.getPageSize());
        pagingQueryDTO.setConditionList(queryParams);
        pagingQueryDTO.setSortColumnMap(orderByMap);
        PagingQueryDTO resultData = listQueryService.query(pagingQueryDTO, QueryConstants.QUERY_USER_LIST_4_MERCHANT, null);
        return Result.success(resultData);
    }

    @Override
    /**
     * 禁用启用用户
     *
     * @param enable       启用/禁用
     * @param userCode     用户代码
     * @param merchantCode 商户代码
     * @param tenantCode   租户代码
     * @param operatorCode 操作人代码
     * @return
     */
    public Result<Void> enableOrDisableUser(Boolean enable, String userCode, String merchantCode, String tenantCode, String operatorCode) {
        if (userService.enableOrDisableUser(enable, userCode, merchantCode, tenantCode, operatorCode)) {
            return Result.success();
        }
        return Result.fail(ResultCodeEnum.SAVE_DATA_FAILED);
    }

    @Override
    /**
     * 用户下拉数据
     *
     * @param merchantCode
     * @param tenantCod
     * @return
     */
    public Result<List<SimpleEntityVO>> dropDownList(String merchantCode, String tenantCod) {
        List<UserDO> userDOList = userService.getUserByMerchant(merchantCode, tenantCod);
        if (userDOList == null || userDOList.isEmpty()) {
            return Result.success(new ArrayList<>());
        }
        return Result.success(userDOList.stream().map(t -> new SimpleEntityVO(t.getCode(), t.getNumber(), t.getName())).collect(Collectors.toList()));
    }

    @Override
    /**
     * 删除用户
     *
     * @param userCode
     * @param merchantCode
     * @param tenantCode
     * @return
     */
    public Result<Void> removeUser(String userCode, String merchantCode, String tenantCode) {
        if (userService.removeUser(userCode, merchantCode, tenantCode)) {
            return Result.success();
        }
        return Result.fail(ResultCodeEnum.REMOVE_FAILED);
    }

    @Override
    /**
     * 修改密码
     *
     * @param userCode        用户代码
     * @param historyPassword 历史密码
     * @param password        新密码
     * @return
     */
    public Result<Void> updatePassword(String userCode, String historyPassword, String password) {
        if (userService.updatePassword(userCode, historyPassword, password)) {
            return Result.success();
        }
        return Result.fail(ResultCodeEnum.SAVE_DATA_FAILED);
    }

    @Override
    /**
     * 重置密码
     *
     * @param userCode     用户代码
     * @param merchantCode 商户代码
     * @return
     */
    public Result<Void> resetPassword(String userCode, String merchantCode) {
        if (userService.resetPassword(userCode, merchantCode)) {
            return Result.success();
        }
        return Result.fail(ResultCodeEnum.SAVE_DATA_FAILED);
    }

    @Override
    /**
     * 根据用户电话号码精确匹配商户信息(作为登录选择)
     *
     * @param phone
     * @return
     */
    public Result<List<MerchantLoginUserVO>> getMerchantUserByPhone(String phone) {
        List<MerchantLoginUserVO> result = userService.getMerchantUserByPhone(phone);
        if (result == null) {
            return Result.fail(ResultCodeEnum.HAS_NOT_PERMISSION);
        }
        return Result.success(result);
    }


}
